<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="java.sql.Statement" %>
<%@page trimDirectiveWhitespaces="true"%>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager" %>
<%@ page language="java" import="java.lang.*" %>
<%@ page import = "java.sql.SQLException" %>
<%@ page import = "com.seniorproject.aims.*" %>
<%@ page import = "java.util.List" %>
<%@ page import = "java.util.ArrayList"%>
<%@ page import = "java.util.Properties" %>
<%@ page import = "javax.servlet.ServletContext" %>
<%@ page import = "java.io.*" %>
<%@page import="java.util.regex.Matcher"%>
<%@page import="java.util.regex.Pattern"%>

<%

	//get session
	String strUser = String.valueOf(session.getAttribute("sUser"));
	HttpSession htp_session = request.getSession();
	String name = String.valueOf(session.getAttribute("name_th"));
	String surname = String.valueOf(session.getAttribute("surname_th"));
	
	//check session
	if (htp_session == null || htp_session.getAttribute("sUser") == null) {
	    // Forward the control to login.jsp if authentication fails or session expires
	    request.getRequestDispatcher("/login.jsp").forward(request,
	        response);
	}
	if("admin".equals(htp_session.getAttribute("sUser"))){%>
		<script>alert("This user dont have PERMISSION to access this zone.");</script>
		<meta HTTP-EQUIV="Refresh" CONTENT="0; URL=admin_home.jsp"> 	
	<%}

	System.out.println("in enrollment SAVE :");////////////////try////////////////
	//get value from tag
	String student_id =  request.getParameter("student_id");
	int count_course = Integer.parseInt(request.getParameter("count_course"));
	String[] class_id = new String[count_course];
	String[] enroll_type = new String[count_course];
	String[] grade = new String[count_course];
			
	System.out.println("student_id :" + student_id);////////////////try////////////////
	System.out.println("count_course :" + count_course);////////////////try////////////////
	
	for(int i=0; i<count_course; i++) {
		class_id[i] = request.getParameter("class_id_"+i);
		enroll_type[i] = request.getParameter("enroll_type_"+i);
		grade[i] = request.getParameter("grade_"+i);
		
		System.out.println("class_id "+i+" : " + class_id[i]);////////////////try////////////////
		System.out.println("enroll_type "+i+" : " + enroll_type[i]);////////////////try////////////////
		System.out.println("grade "+i+" : " + grade[i]);////////////////try////////////////
	}
	
	//set Database Connection
	String hostProps = "";
	String usernameProps  = "";
	String passwordProps  = "";
	String databaseProps = "";
	
	try {
		//get current path
		ServletContext servletContext = request.getSession().getServletContext();
		
		InputStream input = servletContext.getResourceAsStream("/properties/connectDB.properties");
		Properties props = new Properties();
		
		props.load(input);

		hostProps  = props.getProperty("host");
		usernameProps  = props.getProperty("username");
		passwordProps  = props.getProperty("password");
		databaseProps = props.getProperty("database");
	} catch (Exception e) { 
		out.println(e);  
	}
	
	// connect database
	Connection connect = null;		
	try {
		Class.forName("com.mysql.jdbc.Driver");
	
		connect =  DriverManager.getConnection("jdbc:mysql://" + hostProps  + "/" + databaseProps +
				"?user=" + usernameProps  + "&password=" + passwordProps+ "&characterEncoding=tis620");
		
		if(connect != null){
			System.out.println("Database Connect Sucesses.");
		} else {
			System.out.println("Database Connect Failed.");	
		}

	} catch (Exception e) {
		out.println(e.getMessage());
		e.printStackTrace();
	}
	
		
	try {	
		int count = 0; // count row fail
		List<Integer> error_list = new ArrayList<Integer>();
		
		for(int i=0; i<count_course; i++ ) {
			
			String sql = "SELECT *" +
					" FROM enrollment"+
					" WHERE student_id='"+student_id+"' AND class_id='"+class_id[i]+"'";
			
			System.out.println(sql);/////try///
			
			ResultSet rs = connect.createStatement().executeQuery(sql);	
				
						
			if(rs.next()) {			
				//out.print("fail");
				error_list.add(i+1);
				count++;
				System.out.println("ADD");
			}
			else {			
				String sql_enroll = "INSERT INTO `enrollment`( `student_id`, `class_id`, `grade`, `type_of_enrollment`)" 
						+ " VALUES ( '"+student_id+ "', "+class_id[i]+", '"+grade[i]+"', '"+enroll_type[i]+"' )";	
				
				System.out.println(sql_enroll);/////try///
				
				/* Log file */
				String log = strUser+" "+name+" "+surname+" add enrollment";
				Log.writeUserFile(log);
				Log.writeUserFile(sql_enroll);
				
				connect.createStatement().executeUpdate(sql_enroll);
			}
		}
		if(count == 0) {
			out.print("success");
		}
		else {
			//String error = "fail:";
			out.print("fail");
		}
	} catch (SQLException e) {
		out.print("fail");
		
		e.printStackTrace();
	}
		
	connect.close();
%>